<?php

namespace app\api\controller;

use app\admin\model\Consultants;
use app\admin\model\Dealcase;
use app\admin\model\Helpcenter;
use app\admin\model\Houses;
use app\admin\model\member\Rights;
use app\admin\model\user\Browses;
use app\admin\model\user\Collect;
use app\common\library\xmwechat\offiaccount\MessageService;
use app\common\model\imchat\Message;
use app\common\model\UserCollect;
use ba\Tree;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Throwable;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\Config;
use app\common\controller\Frontend;

#[Apidoc\Title("首页接口")]
class Index extends Frontend
{
    protected array $noNeedLogin = ["*"];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 前台和会员中心的初始化请求
     * @throws Throwable
     */
    public function index(): void
    {
        $menus = [];
        if ($this->auth->isLogin()) {
            $rules = [];
            $userMenus = $this->auth->getMenus();

            // 首页加载的规则，验权，但过滤掉会员中心菜单
            foreach ($userMenus as $item) {
                if ($item['type'] == 'menu_dir') {
                    $menus[] = $item;
                } else if ($item['type'] != 'menu') {
                    $rules[] = $item;
                }
            }
            $rules = array_values($rules);
        } else {
            // 若是从前台会员中心内发出的请求，要求必须登录，否则会员中心异常
            $requiredLogin = $this->request->get('requiredLogin/b', false);
            if ($requiredLogin) {
                $token = $this->request->server('HTTP_BA_USER_TOKEN', $this->request->request('ba-user-token', Cookie::get('ba-user-token') ?: false));

                // 若过期可触发过期判定
                $this->auth->init($token);

                // 未过期或无token，直接要求登录
                $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }

            $rules = Db::name('user_rule')
                ->where('status', '1')
                ->where('no_login_valid', 1)
                ->where('type', 'in', ['route', 'nav', 'button'])
                ->order('weigh', 'desc')
                ->select()
                ->toArray();
            $rules = Tree::instance()->assembleChild($rules);
        }

        $this->success('', [
            'site' => [
                'siteName' => get_sys_config('site_name'),
                'recordNumber' => get_sys_config('record_number'),
                'version' => get_sys_config('version'),
                'cdnUrl' => full_url(),
                'upload' => get_upload_config(),
            ],
            'openMemberCenter' => Config::get('buildadmin.open_member_center'),
            'userInfo' => $this->auth->getUserInfo(),
            'rules' => $rules,
            'menus' => $menus,
        ]);
    }

    #[
        Apidoc\Title("首页头部信息和未读消息数量 未登录 unread_msg 默认为0"),
        Apidoc\Method("get")
    ]
    public function getinfo(): void
    {

        $unread_message_num = 0;
        if ($this->auth->isLogin()) {
            $unread_message_num = (new Message())
                ->where('to_uid', $this->auth->id)
                ->where(['status' => "0"])
                ->count();
        }
        $this->success('', [
            'recommend_num' => (new \app\common\model\Config())->where('id', 16)->value('value'),
            'unread_msg' => $unread_message_num
        ]);
    }

    #[
        Apidoc\Title("首页tab1转让出租 新版本3.0"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/transferLeasing"),
        Apidoc\Query(name: "keyword", type: "string", require: false, desc: "关键词搜索", mock: ""),
        Apidoc\Query(name: "longitude", type: "string", require: true, desc: "经度", mock: "25.102685"),
        Apidoc\Query(name: "latitude", type: "string", require: true, desc: "纬度", mock: "102.674829"),
        //Apidoc\Query(name:"tab",type: "string",require: true,desc: "类型（rent=转让出租，attract=求租，case=成交案列）",mock:"rent"),
        Apidoc\Query(name: "start_acreage", type: "number", desc: "起始面积", mock: ""),
        Apidoc\Query(name: "end_acreage", type: "number", desc: "结束面积", mock: ""),
        Apidoc\Query(name: "category_ids", type: "string", desc: "房源类型1,2,3", mock: ""),
        Apidoc\Query(name: "industry", type: "string", desc: "行业1,2,3", mock: ""),
        Apidoc\Query(name: "city", type: "id", desc: "地区（最后一个id）", mock: ""),
        Apidoc\Query(name: "page", type: "number", desc: "页码", mock: "1"),
        Apidoc\Query(name: "order_rule", type: "number", desc: "排序规则 1:智能排序，2时间排序", mock: ""),
        Apidoc\Query(name: "is_vip", type: "number", desc: "0否1是", mock: "0"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("has_bounty", type: "int", desc: "是否悬赏:0=否,1=是"),
        Apidoc\Returned("is_vip", type: "int", desc: "是否VIP房源:0=否,1=是"),
        Apidoc\Returned("reward", type: "float", desc: "悬赏金额"),
        Apidoc\Returned("name", type: "string", desc: "房源名称"),
        Apidoc\Returned("name", type: "string", desc: "房源名称"),
        Apidoc\Returned("distance", type: "string", desc: "距离"),
        Apidoc\tag("acreage	面积</br>
address	详情地址
category_ids	房源类型
city	城市选择
create_time	创建时间
files	视频
has_bounty	是否悬赏:0=否,1=是
id	ID
images	图片
industry	行业
latitude	纬度
longitude	经度
name	名称
property	物业
rent_free	免租期月
rent_money	租金
reward	悬赏金额
start_rent	起租 几个月
status	状态:0=禁用,1=启用
surround	周边配套
tags_ids	标签"),

    ]
    public function transferLeasing(): void
    {
        $order_rule = $this->request->param('order_rule', 'reward');
        if (empty($this->request->param('longitude')) || empty($this->request->param('latitude'))) {
            //  $this->error('经纬度不能为空');
        }
        $map = [
            ['status', '=', '1']
        ];
        $latitude = $this->request->param('latitude');
        $longitude = $this->request->param('longitude');

        $sql_raw = '';
        $start_acreage = $this->request->param('start_acreage');
        $end_acreage = $this->request->param('end_acreage');

        $category_ids = $this->request->param('category_ids');
        $area = $this->request->param('city');
        $industry = $this->request->param('industry');
        if (!empty($start_acreage)) {
            $map[] = ['acreage', '>=', $start_acreage];
        }
        if (!empty($end_acreage)) {
            $map[] = ['acreage', '<=', $end_acreage];
        }
        if (!empty($category_ids)) {
            $category_ids = explode(',', $category_ids);
            if ($sql_raw) {
                $sql_raw .= ' and (';
            } else {
                $sql_raw = '(';
            }
            foreach ($category_ids as $key => $value) {
                $sql_raw .= 'FIND_IN_SET(' . $value . ',category_ids) OR ';
            }
            $sql_raw = trim($sql_raw, 'OR ');
            $sql_raw .= ')';
            //$map[] = ['category_ids', 'in', $category_ids];
        }
        if (!empty($industry)) {
            $industry = explode(',', $industry);
            if ($sql_raw) {
                $sql_raw .= ' and (';
            } else {
                $sql_raw = '(';
            }
            foreach ($industry as $key => $value) {
                $sql_raw .= 'FIND_IN_SET(' . $value . ',industry) OR ';
            }
            $sql_raw = trim($sql_raw, 'OR ');
            $sql_raw .= ')';
            //$map[] = ['industry', 'in', $industry];
        }
        if ($area) {
            $area = explode(',', $area);
            if ($sql_raw) {
                $sql_raw .= ' and (';
            } else {
                $sql_raw = '(';
            }
            foreach ($area as $key => $value) {
                if (is_numeric($value)) {
                    $sql_raw .= 'FIND_IN_SET(' . $value . ',city) OR ';
                }
            }
            $sql_raw = trim($sql_raw, 'OR ');
            $sql_raw .= ')';
            //$map[] = ['city', 'like', '%' . $area . '%'];
        }
        $is_vip = $this->request->param('is_vip');
        if ($is_vip) {
            $map[] = ['is_vip', '=', 1];
        }
        if ($order_rule == 1) {
            $order_filed = 'weigh desc';
        } else if ($order_rule == 2) {
            $order_filed = 'create_time desc';
        } else {
            $order_filed = 'weigh desc,reward desc';
        }
        $keyword = $this->request->param('keyword');
        if (!empty($keyword)) {
            $map[] = ['name|introduction', 'like', '%' . $keyword . '%'];
        }
        $query = (new Houses());
        if ($sql_raw) {
            $query = $query->whereRaw($sql_raw);
        }
        $lists = $query
            ->where($map)
            ->order($order_filed)
            ->paginate();
        $sortdistance = [];

//        $houses_list = [];
//        foreach ($lists->items() as &$item) {
//            $distance = $this->getDistance(floatval($item['latitude']), floatval($item['longitude']), $latitude, $longitude);
//            $sortdistance[] = $distance;
//            $item['distance'] = $distance . 'km';
//            $houses_list[] = $item;
//        }
//        array_multisort($sortdistance, SORT_ASC, $houses_list);
        (new \app\common\model\Config())->where('id', 16)->setInc('value');

        $return = ['current_page' => $lists->currentPage(),
            'data' => $lists->items(),
            'last_page' => $lists->lastPage(),
            'per_page' => $lists->listRows(),
            'total' => $lists->total(),
        ];

        $this->success('成功', $return);
    }


    /*返回千米*/
    private function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        //地球半径
        $R = 6378137;
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        //结果
        $s = acos(cos($radLat1) * cos($radLat2) * cos($radLng1 - $radLng2) + sin($radLat1) * sin($radLat2)) * $R;
        //精度
        return bcdiv($s, 1000, 2) . 'm';
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    #[
        Apidoc\Title("转让出租详情"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/rentDetail"),
        Apidoc\Param(name: "longitude", type: "string", require: true, desc: "经度", mock: "25.102685"),
        Apidoc\Param(name: "latitude", type: "string", require: true, desc: "纬度", mock: "102.674829"),

        Apidoc\Param(name: "id", type: "number", require: true, desc: "房源id", mock: "2"),
        Apidoc\Returned("is_collect", type: "int", desc: "是否收藏:0=否,1=是"),
        Apidoc\Returned("similar_houses", type: "array", desc: "相似房源"),
    ]
    public function rentDetail(): void
    {

        $latitude = $this->request->param('latitude');
        $longitude = $this->request->param('longitude');
        $id = $this->request->param('id');
        if (empty($this->request->param('id'))) {
            $this->error('房源不能为空');
        }
        $map = [
            // ['status', '=', '1'],
            ['id', '=', $this->request->param('id')]
        ];
        $houses_list = (new Houses())
            ->where($map)
            ->with(['user'])
            ->find();
        if (!$houses_list) {
            $this->error('房源不存在' . $id);
        }
        $houses_list['is_collect'] = (new Collect())->where(['houses_id' => $houses_list['id'], 'user_id' => $this->auth->id, 'type' => 'house'])->count('id');
        $houses_list->visible(['user' => ['nickname', 'avatar', 'domain_avtar', 'motto', 'id', 'mobile', 'uuid']]);
        $latitude = $this->request->param('latitude');
        $longitude = $this->request->param('longitude');
        $distance = $this->getDistance(floatval($houses_list['latitude']), floatval($houses_list['longitude']), $latitude, $longitude);
        $houses_list['distance'] = $distance;
        $houses_list['similar_houses'] = (new Houses())
            ->where([
                ['status', '=', 1],
                ['id', '<>', $id],
            ])->where(function ($query) use ($houses_list) {
                $query->whereOr([['acreage', '>=', $houses_list['acreage'] - 50]])
                    ->whereOr([['acreage', '>=', $houses_list['acreage'] + 50]]);;
            })
            ->where(function ($query) use ($houses_list) {
                $query->whereOr([['rent_money', '>=', $houses_list['rent_money'] - 400]])
                    ->whereOr([['rent_money', '>=', $houses_list['rent_money'] + 400]]);;
            })
            ->order('reward', 'desc')
            ->limit(10)->select();
        $houses_list['dealer_info'] = '';
        if ($houses_list['status'] == 4) {
            $dealer_id = (new \app\admin\model\Orders())
                ->where('id', $houses_list['order_id'])
//                ->where([
//                    'house_id' => $houses_list['id'],
//                    'pay_status' => 1,
//                    'house_type' => 'houses'
//                ])
                ->value('to_uid');
            $houses_list['dealer_info'] = (new \app\admin\model\User())->where(['id' => $dealer_id])->find();
        }
        if($houses_list['is_vip']==1){
            $houses_list['user']['mobile']="138****1234";
        }
        $this->success('成功', $houses_list);
    }

    #[
        Apidoc\Title("转让出租 用户收藏"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/collectRent"),
        Apidoc\Param(name: "id", type: "number", require: true, desc: "房源id", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("22", type: "int", desc: "aaad"),
    ]
    public function collectRent(): void
    {
        if (empty($this->request->param('id'))) {
            $this->error('房源不能为空');
        }
        $map = [
            ['status', '=', '1'],
            ['id', '=', $this->request->param('id')]
        ];
        $houses_list = (new Houses())->where($map)->find();
        if (!$houses_list) {
            $this->error('房源不存在');
        }
        $res = (new UserCollect())->where([
            'user_id' => $this->auth->id,
            'houses_id' => $this->request->param('id'),
            'type' => 'house'
        ])->find();
        if ($res) {
            $res->delete();
            $this->success('取消收藏');
            $this->error('已收藏过');
        }
        (new UserCollect())->create([
            'user_id' => $this->auth->id,
            'houses_id' => $this->request->param('id'),
            'type' => 'house'
        ]);
        $this->success('成功');
    }

    #[
        Apidoc\Title("首页tab2客户找房"),
        Apidoc\Tag("create_time	添加时间
end_area	面积范围
end_rent	租金范围
id	ID
name	标题
rent_unit	租金单位:0=元/月,1=元/㎡/月
reward	悬赏佣金
start_area	面积范围
start_rent	租金范围
status	状态:0=禁用,1=启用
update_time	创建时间
user_id	所属用户
weigh	权重"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/findhouse"),

        Apidoc\Param(name: "keyword", type: "string", require: false, desc: "关键词搜索", mock: ""),
        Apidoc\Param(name: "longitude", type: "string", require: true, desc: "经度", mock: ""),
        Apidoc\Param(name: "latitude", type: "string", require: true, desc: "纬度", mock: ""),
        //Apidoc\Query(name:"tab",type: "string",require: true,desc: "类型（rent=转让出租，attract=求租，case=成交案列）",mock:"rent"),
        Apidoc\Param(name: "start_acreage", type: "number", desc: "起始面积", mock: "1"),
        Apidoc\Param(name: "end_acreage", type: "number", desc: "结束面积", mock: "1"),

        Apidoc\Query(name: "industry", type: "string", desc: "行业1,2,3", mock: ""),
        Apidoc\Query(name: "city", type: "id", desc: "地区（最后一个id）", mock: ""),
        Apidoc\Param(name: "category_ids", type: "string", desc: "房源类型1,2,3", mock: "1,2,3"),
        Apidoc\Param(name: "page", type: "number", desc: "页码", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("22", type: "int", desc: "aaad"),
    ]
    public function findhouse(): void
    {
        if (empty($this->request->param('longitude')) || empty($this->request->param('latitude'))) {
            //  $this->error('经纬度不能为空');
        }
        $map = [
            ['status', '=', '1']
        ];
        if (!empty($this->request->param('longitude')) && !empty($this->request->param('latitude'))) {
            $map[] = ['longitude', 'BETWEEN', [$this->request->get('longitude') - 0.005, $this->request->get('longitude') + 0.005]]; // 范围
            $map[] = ['latitude', 'BETWEEN', [$this->request->get('latitude') - 0.005, $this->request->get('latitude') + 0.005]]; // 范围
        }
        $keyword = $this->request->param('keyword');
        if (!empty($keyword)) {
            $map[] = ['name', 'like', '%' . $keyword . '%'];
        }

        $area = $this->request->param('city');
        $industry = $this->request->param('industry');
        if (!empty($industry)) {
            $map[] = ['industry', 'in', $industry];
        }
        if ($area) {
            $map[] = ['city', 'like', '%' . $area . '%'];
        }
        $keyword = $this->request->param('keyword');
        if (!empty($keyword)) {
            $map[] = ['name', 'like', '%' . $keyword . '%'];
        }
        $houses_list = (new \app\common\model\Findstore())
            ->with(['user'])
            ->where($map)
            ->order('reward', 'desc')
            ->paginate()->each(function ($item) {
                $item->visible(['user' => ['nickname', 'avatar', 'domain_avtar', 'motto', 'id', 'mobile', 'uuid']]);
            });
        $this->success('成功', $houses_list);
    }

    #[
        Apidoc\Title("首页tab3成交案列 字段和tab1一致"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/dealcase"),
        Apidoc\Param(name: "keyword", type: "string", require: false, desc: "关键词搜索", mock: ""),
        Apidoc\Param(name: "longitude", type: "string", require: true, desc: "经度", mock: ""),
        Apidoc\Param(name: "latitude", type: "string", require: true, desc: "纬度", mock: ""),
        //Apidoc\Query(name:"tab",type: "string",require: true,desc: "类型（rent=转让出租，attract=求租，case=成交案列）",mock:"rent"),
        Apidoc\Param(name: "start_acreage", type: "number", desc: "起始面积", mock: "1"),
        Apidoc\Param(name: "end_acreage", type: "number", desc: "结束面积", mock: "1"),
        Apidoc\Param(name: "category_ids", type: "string", desc: "房源类型1,2,3", mock: "1,2,3"),

        Apidoc\Query(name: "industry", type: "string", desc: "行业1,2,3", mock: ""),
        Apidoc\Query(name: "city", type: "id", desc: "地区（最后一个id）", mock: ""),
        Apidoc\Param(name: "page", type: "number", desc: "页码", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("22", type: "int", desc: "aaad"),
    ]
    public function dealcase(): void
    {
        file_put_contents('test.txt', json_encode($this->request->param()));
        $order_rule = $this->request->param('order_rule');
        if (empty($this->request->param('longitude')) || empty($this->request->param('latitude'))) {
            //  $this->error('经纬度不能为空');
        }
        $map = [
            ['status', '=', '1']
        ];

        $keyword = $this->request->param('keyword');
        if (!empty($keyword)) {
            $map[] = ['name', 'like', '%' . $keyword . '%'];
        }
        $latitude = $this->request->param('latitude', '25.043273');
        $longitude = $this->request->param('longitude', '102.722497');
        $start_acreage = $this->request->param('start_acreage');
        $end_acreage = $this->request->param('end_acreage');
        $category_ids = $this->request->param('category_ids');
        $area = $this->request->param('city/a');
        $industry = $this->request->param('industry');
        if (!empty($start_acreage)) {
            $map[] = ['acreage', '>=', $start_acreage];
        }
        if (!empty($end_acreage)) {
            $map[] = ['acreage', '<=', $end_acreage];
        }
        if (!empty($category_ids)) {
            $map[] = ['category_ids', 'in', $category_ids];
        }
        if (!empty($industry)) {
            $map[] = ['industry', 'in', $industry];
        }
        if ($area) {// 最后一个
            // $map[] = ['city', 'like', '%' . $area . '%'];
        }
        if ($order_rule == 1) {
            $order_filed = 'weigh';
        } else {
            $order_filed = 'create_time';
        }
        $lists = (new Dealcase())->where($map)
            ->order($order_filed, 'desc')
            ->paginate();
        $sortdistance = [];

        $houses_list = [];
        foreach ($lists->items() as &$item) {
            if ($item['latitude'] && $item['longitude']) {
                $distance = 0;// $this->getDistance(floatval($item['latitude']), floatval($item['longitude']), $latitude, $longitude);
            } else {
                $distance = 0;
            }
            $sortdistance[] = $distance;
            $item['distance'] = $distance . 'km';
            $houses_list[] = $item;
        }
        //array_multisort($sortdistance, SORT_ASC, $houses_list);

        $result_arr = [
            "total" => $lists->total(),
            "per_page" => $lists->listRows(),
            "current_page" => $lists->currentPage(),
            "last_page" => $lists->lastPage(),
            "data" => $houses_list
        ];
        $this->success('成交案列', $result_arr);
    }

    #[
        Apidoc\Title("成交案列详情"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/caseDetail"),
        Apidoc\Param(name: "id", type: "number", require: true, desc: "房源id", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("22", type: "int", desc: "aaad"),
    ]
    public function caseDetail(): void
    {
        if (empty($this->request->param('id'))) {
            $this->error('房源不能为空');
        }
        $map = [
            //['status', '=', '1'],
            ['id', '=', $this->request->param('id')]
        ];
        $houses_list = (new Dealcase())
            ->where($map)
            ->with(['user'])
            ->find();
        if (!$houses_list) {
            $this->error('房源不存在' . $this->request->param('id'));
        }
        $houses_list->visible(['user' => ['nickname', 'avatar', 'domain_avtar', 'motto', 'id', 'mobile', 'uuid']]);
        $latitude = $this->request->param('latitude');
        $longitude = $this->request->param('longitude');
        $distance = $this->getDistance(floatval($houses_list['latitude']), floatval($houses_list['longitude']), $latitude, $longitude);

        $this->success('成功', $houses_list);
    }

    public function test(): void
    {
        MessageService::getInstance()->getUnionid();
        $this->success('成功');
    }

    public function helpcenter()
    {
        $row = (new Helpcenter())->where('status', '=', 1)->where('id', '=', 1)->find();
        $this->success('成功', $row);
    }

    #[
        Apidoc\Title("会员权益 版本3.0"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/mermberrights"),
        Apidoc\Param(name: "id", type: "number", require: true, desc: "会员权益 等于2：介绍页面；等于3：查看价格购买页面", mock: "2"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("22", type: "int", desc: "aaad"),
        Apidoc\Returned("rights", type: "array", desc: "id等于3 才有  权益信息
        benefit	享受权益内容
current_price	现价
id	ID g购买时候用
original_price	原价
status	状态:0=禁用,1=启用
title	标题
validity_period	有效期 天
view_items	一天可以看多少条"),
    ]
    public function mermberrights()
    {
        $id = $this->request->param('id/d');
        $row = (new Helpcenter())
            ->where('status', '=', 1)
            ->where('id', '=', $id)
            ->find();
        if ($id == 3) {
            $row['rights'] = (new Rights())
                ->order('weigh', 'desc')
                ->select();
        }
        $this->success('会员权益', $row);
    }

    #[
        Apidoc\Title("团队顾问  版本3.0"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/consultants"),
        Apidoc\Param(name: "page", type: "number", require: true, desc: "分页数据默认第一页", mock: "1"),
        Apidoc\Returned("id", type: "int", desc: "Id"),
        Apidoc\Returned("name", type: "string", desc: "姓名"),
        Apidoc\Returned("image", type: "string", desc: "头像"),
        Apidoc\Returned("domain_image", type: "string", desc: "带域名头像"),
        Apidoc\Returned("good_at", type: "string", desc: "擅长"),
        Apidoc\Returned("phone", type: "string", desc: "联系电话"),
    ]
    public function consultants()
    {
        $list = (new Consultants())
            ->order('weigh', 'desc')
            ->paginate();
        $this->success('团队顾问', $list);
    }


    /**
     * 联系房东 版本3.0 返回
     */
    #[
        Apidoc\Title("联系房东 版本3.0"),
        Apidoc\Tag("apidoc,基础,示例"),
        Apidoc\Method("POST"),
        Apidoc\Url("/api/index/contactLand"),
        Apidoc\Param(name: "id", type: "number", require: true, desc: "房源对应的详情id 找房对应的详情id", mock: "2"),
        Apidoc\Param(name: "type", type: "string", require: "true", desc: "对应的类型  houses 转让出租', 'findstore =找房公告'", mock: "houses"),
        Apidoc\Returned("返回房东电话", type: "array", desc: ""),
    ]
    public function contactLand()
    {
        $id = $this->request->param('id/d');
        $type = $this->request->param('type');
        Db::instance();
        $noinfo=(new \app\admin\model\User())->where('id','=',$this->auth->id)->find();
        if($this->auth->isvip==1){
            if($noinfo['expired_time']<=time()){
                $this->error('您的会员已过期');
            }
            if($noinfo['dodayview_items']<=0){
                $this->error('您查看次数已用完');
            }
            $brologs=(new Browses())->where([
                ['type','=',$type],
                ['user_id' ,'=',$this->auth->id],['houses_id','=',$id]
            ])->find();
            if(!$brologs){
                //已经看过的就不用消耗了
               $noinfo->save([
                    'dodayview_items'=>$noinfo['dodayview_items']-1
                ]);
            }else{

            }
        }
        else{
            $paylogs=(new \app\admin\model\Orders())->where([
                'house_id'=>$id,
                'user_id'=>$this->auth->id,
                'house_type'=>$type,
                'pay_status'=>1,
                'version'=>2
            ])->find();
            if(!$paylogs){
                $this->error('您没有支付查看');
            }
        }
        (new Browses())->save([
            'update_time' => time(),
            'create_time' => time(),
            'type' => $type,
            'user_id' => $this->auth->id,
            'houses_id' => $id,
        ]);
        Db::commit();
        $contact_phone='13888888888';
        if($type=='houses'){
            $hourserow=(new Houses())->with('user')->find($id);
            $contact_phone=$hourserow['user']['mobile'];
        }else if($type=='findstore'){
            $hourserow=(new \app\common\model\Findstore())->with('user')->find($id);
            $contact_phone=$hourserow['user']['mobile'];
        }
        $this->success('获取联系房东电话',[
            'phone'=>$contact_phone
        ]);
    }
}
